import { getOrders, createOrder, cancelOrder } from '@/api/order'

const state = {
  orders: []
}

const mutations = {
  setOrders(state, orders) {
    state.orders = orders
  },
  addOrder(state, order) {
    state.orders.push(order)
  },
  removeOrder(state, orderId) {
    state.orders = state.orders.filter(order => order.id !== orderId)
  }
}

const actions = {
  async fetchOrders({ commit }) {
    try {
      const response = await getOrders()
      commit('setOrders', response.data)
      return response
    } catch (error) {
      throw error
    }
  },
  async createOrder({ commit }, payload) {
    try {
      const response = await createOrder(payload)
      commit('addOrder', response.data)
      return response
    } catch (error) {
      throw error
    }
  },
  async cancelOrder({ commit }, orderId) {
    try {
      await cancelOrder(orderId)
      commit('removeOrder', orderId)
    } catch (error) {
      throw error
    }
  }
}

const getters = {
  allOrders(state) {
    return state.orders
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
